<template>
	<view class="address-edit-container">
		<form @submit="handleSubmit">
			<view class="form-section">
				<view class="form-item">
					<text class="form-label">收货人</text>
					<input 
						class="form-input" 
						v-model="formData.recipient_name" 
						placeholder="请输入收货人姓名"
						maxlength="20"
					/>
				</view>

				<view class="form-item">
					<text class="form-label">手机号</text>
					<input 
						class="form-input" 
						v-model="formData.phone_number" 
						placeholder="请输入手机号"
						type="number"
						maxlength="11"
					/>
				</view>

				<view class="form-item">
					<text class="form-label">所在地区</text>
					<view class="region-picker" @click="showRegionPicker">
						<text class="region-text" :class="{ placeholder: !regionText }">
							{{ regionText || '请选择省市区' }}
						</text>
						<text class="picker-arrow">></text>
					</view>
				</view>

				<view class="form-item">
					<text class="form-label">详细地址</text>
					<textarea 
						class="form-textarea" 
						v-model="formData.detailed_address" 
						placeholder="请输入详细地址，如街道、门牌号等"
						maxlength="200"
						:show-count="true"
					/>
				</view>

				<view class="form-item checkbox-item">
					<checkbox 
						:checked="formData.is_default" 
						@click="toggleDefault"
						color="#D4AF37"
					/>
					<text class="checkbox-label">设为默认地址</text>
				</view>
			</view>

			<view class="form-actions">
				<button class="save-btn" @click="handleSubmit">保存地址</button>
			</view>
		</form>

		<!-- 地区选择器 -->
		<RegionPicker
			:visible="showPicker"
			:value="regionValue"
			@confirm="onRegionChange"
			@cancel="hidePicker"
		/>
	</view>
</template>

<script>
import { get, post, put, showLoading, hideLoading } from '@/utils/request.js'
import RegionPicker from '@/components/RegionPicker.vue'

export default {
	components: {
		RegionPicker
	},
	data() {
		return {
			addressId: null,
			isEdit: false,
			showPicker: false,
			formData: {
				recipient_name: '',
				phone_number: '',
				province: '',
				city: '',
				district: '',
				detailed_address: '',
				is_default: false
			},
			regionValue: []
		}
	},
	computed: {
		regionText() {
			if (this.formData.province && this.formData.city && this.formData.district) {
				return `${this.formData.province} ${this.formData.city} ${this.formData.district}`;
			}
			return '';
		}
	},
	onLoad(options) {
		if (options.id) {
			this.addressId = parseInt(options.id);
			this.isEdit = true;
			this.loadAddressDetail();
		}
		
		// 设置页面标题
		uni.setNavigationBarTitle({
			title: this.isEdit ? '编辑地址' : '添加地址'
		});
	},
	methods: {
		// 加载地址详情
		async loadAddressDetail() {
			try {
				showLoading('加载中...');
				const res = await get(`/addresses/${this.addressId}`);
				const address = res.data;
				
				this.formData = {
					recipient_name: address.recipient_name,
					phone_number: address.phone_number,
					province: address.province,
					city: address.city,
					district: address.district,
					detailed_address: address.detailed_address,
					is_default: address.is_default
				};
				
				// 设置地区选择器的值
				this.regionValue = [address.province, address.city, address.district];
			} catch (error) {
				console.error('加载地址详情失败:', error);
				uni.showToast({
					title: error.message || '加载失败',
					icon: 'none'
				});
			} finally {
				hideLoading();
			}
		},

		// 显示地区选择器
		showRegionPicker() {
			this.showPicker = true;
		},

		// 隐藏地区选择器
		hidePicker() {
			this.showPicker = false;
		},

		// 地区选择变化
		onRegionChange(regionData) {
			this.formData.province = regionData.province;
			this.formData.city = regionData.city;
			this.formData.district = regionData.district;
			this.regionValue = regionData.value;
			this.showPicker = false;
		},

		// 切换默认地址
		toggleDefault() {
			this.formData.is_default = !this.formData.is_default;
		},

		// 表单验证
		validateForm() {
			if (!this.formData.recipient_name.trim()) {
				uni.showToast({
					title: '请输入收货人姓名',
					icon: 'none'
				});
				return false;
			}

			if (!this.formData.phone_number.trim()) {
				uni.showToast({
					title: '请输入手机号',
					icon: 'none'
				});
				return false;
			}

			const phoneRegex = /^1[3-9]\d{9}$/;
			if (!phoneRegex.test(this.formData.phone_number)) {
				uni.showToast({
					title: '请输入正确的手机号',
					icon: 'none'
				});
				return false;
			}

			if (!this.formData.province || !this.formData.city || !this.formData.district) {
				uni.showToast({
					title: '请选择所在地区',
					icon: 'none'
				});
				return false;
			}

			if (!this.formData.detailed_address.trim()) {
				uni.showToast({
					title: '请输入详细地址',
					icon: 'none'
				});
				return false;
			}

			return true;
		},

		// 提交表单
		async handleSubmit() {
			if (!this.validateForm()) {
				return;
			}

			try {
				showLoading(this.isEdit ? '保存中...' : '添加中...');
				
				if (this.isEdit) {
					await put(`/addresses/${this.addressId}`, this.formData);
				} else {
					await post('/addresses', this.formData);
				}
				
				uni.showToast({
					title: this.isEdit ? '保存成功' : '添加成功',
					icon: 'success'
				});
				
				// 延迟返回上一页
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
			} catch (error) {
				console.error('保存地址失败:', error);
				uni.showToast({
					title: error.message || '保存失败',
					icon: 'none'
				});
			} finally {
				hideLoading();
			}
		}
	}
}
</script>

<style scoped>
.address-edit-container {
	background-color: #F5F5F5;
	min-height: 100vh;
}

.form-section {
	background-color: #FFFFFF;
	margin: 20rpx;
	border-radius: 16rpx;
	padding: 40rpx 30rpx;
}

.form-item {
	margin-bottom: 40rpx;
}

.form-item:last-child {
	margin-bottom: 0;
}

.form-label {
	display: block;
	font-size: 28rpx;
	color: #333333;
	font-weight: bold;
	margin-bottom: 16rpx;
}

.form-input {
	width: 100%;
	padding: 20rpx;
	border: 2rpx solid #E0E0E0;
	border-radius: 12rpx;
	font-size: 28rpx;
	color: #333333;
	background-color: #FAFAFA;
}

.form-input:focus {
	border-color: #D4AF37;
	background-color: #FFFFFF;
}

.form-textarea {
	width: 100%;
	min-height: 120rpx;
	padding: 20rpx;
	border: 2rpx solid #E0E0E0;
	border-radius: 12rpx;
	font-size: 28rpx;
	color: #333333;
	background-color: #FAFAFA;
	resize: none;
}

.form-textarea:focus {
	border-color: #D4AF37;
	background-color: #FFFFFF;
}

.region-picker {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx;
	border: 2rpx solid #E0E0E0;
	border-radius: 12rpx;
	background-color: #FAFAFA;
}

.region-text {
	font-size: 28rpx;
	color: #333333;
}

.region-text.placeholder {
	color: #999999;
}

.picker-arrow {
	font-size: 24rpx;
	color: #999999;
}

.checkbox-item {
	display: flex;
	align-items: center;
}

.checkbox-label {
	font-size: 28rpx;
	color: #333333;
	margin-left: 16rpx;
}

.form-actions {
	padding: 40rpx;
}

.save-btn {
	width: 100%;
	background-color: #D4AF37;
	color: #FFFFFF;
	border: none;
	border-radius: 50rpx;
	padding: 30rpx;
	font-size: 32rpx;
	font-weight: bold;
}

.save-btn:active {
	background-color: #B8941F;
}
</style>
